import { UploadApi } from '@/common/constants/request-api'

/**
 * 上传文件组合
 * @returns
 */
export const useUploadFile = () => {
  /** 上传状态 */
  const uploading = ref(false)
  /** 错误消息 */
  const errorMessage = ref('')

  /**
   * 调用uploadFile上传头像
   * @param tempFilePath
   */
  const uploadFile = (tempFilePath: string): Promise<string> => {
    return new Promise((resolve, reject) => {
      uploading.value = true
      uni.uploadFile({
        url: import.meta.env.HOPE_API_BASE_URL + UploadApi.UPLOAD,
        filePath: tempFilePath,
        name: 'file',
        success: (res) => {
          const { data } = JSON.parse(res.data)

          resolve(data)
        },
        fail(res) {
          errorMessage.value = `上传失败${res.errMsg}`
          reject(errorMessage.value)
        },
        complete() {
          uploading.value = false
        },
      })
    })
  }

  return {
    /** 上传文件函数 */
    uploadFile,
    /** 错误消息 */
    errorMessage,
    /** 上传状态 */
    uploading,
  }
}
